<template>
  <div class="main_box" style="padding:10px">
    <div class="add_wrapper">
      <div class="title">
        基本信息
      </div>
      <el-form class="el-form__two" :model="dataForm" ref="dataForm" label-width="200px" :rules="roleRules">
        <el-row>
          <!-- 第1行 -->
          <el-form-item prop="businessId" label="商户">
            <el-select class="readonly" :disabled="true" v-model="dataForm.businessId" @change="handleBusinessIdChange"
              clearable filterable>
              <el-option v-for="item in businessList" :key="item.id" :value="item.id" :label="item.name">
              </el-option>
            </el-select>
          </el-form-item>



          <!-- 第2行 -->
          <el-form-item prop="classifyIds" label="产品分类">
            <el-cascader @change="handleClassifyIdsChange" :key="cascaderKey" clearable v-model="dataForm.classifyIds"
              :options="treeThreeServerList" :props="{ label: 'classifyName', value: 'serverClassifyId' }">
            </el-cascader>
          </el-form-item>


          <!-- 第3行 -->
          <el-form-item prop="name" label="产品名称:" placeholder="请输入产品名称">
            <el-input type="text" v-model="dataForm.name" clearable></el-input>
          </el-form-item>

          <el-form-item prop="businessClassifyIds" label='商户分类'>
            <el-select class="business-classify_select"
              v-selectrichtext="{ids:dataForm.businessClassifyIds,list:businessClassifyList}"
                       v-model="dataForm.businessClassifyIds"  clearable filterable multiple>
              <el-option v-for="item in businessClassifyList" :value="item.id" :label="item.name" :key="item.id">
                <div class="business-classify_name" v-html="item.name">

                </div>
              </el-option>
            </el-select>
          </el-form-item>


          <!-- 第4行 -->
          <el-form-item label="部门:" prop="departIds">
            <el-cascader v-model="dataForm.departIds" :options="departList" clearable
              :props="{ value: 'departId', label: 'departName', checkStrictly: true }">

            </el-cascader>
          </el-form-item>

          <el-form-item prop="ghModelId" label='可售时间模板'>
            <el-select v-model="dataForm.ghModelId" @change="handleGhModelIdChange" clearable filterable>
              <el-option v-for="item in goodsHoursList" :label='item.modelName' :value="item.modelId" :key="item.modelId">

              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="businessConfirmWay" label="商户确认方式:">
            <el-select v-model="dataForm.businessConfirmWay">
              <el-option v-for="item in businessConfirmWayList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="visitFlag" label="是否上门:">
            <el-radio v-model="dataForm.visitFlag" :label="1">是</el-radio>
            <el-radio v-model="dataForm.visitFlag" :label="0">否</el-radio>
          </el-form-item>
          <el-form-item prop="shopFlag" label="是否到店:">
            <el-radio v-model="dataForm.shopFlag" :label="1">是</el-radio>
            <el-radio v-model="dataForm.shopFlag" :label="0">否</el-radio>
          </el-form-item>
          <el-form-item prop="remoteFlag" label="是否远程:">
            <el-radio v-model="dataForm.remoteFlag" :label="1">是</el-radio>
            <el-radio v-model="dataForm.remoteFlag" :label="0">否</el-radio>
          </el-form-item>
          <el-form-item prop="fastFlag" label="紧急通知:">
            <el-radio v-model="dataForm.fastFlag" :label="1">是</el-radio>
            <el-radio v-model="dataForm.fastFlag" :label="0">否</el-radio>
          </el-form-item>

        </el-row>
      </el-form>
      <div class="title">
        价格信息
      </div>
      <el-form class="el-form__two" :model="dataForm" ref="dataForm2" label-width="200px" :rules="roleRules">
        <el-row>
          <el-form-item prop="price" label="平台原价:">
            <el-input type="number" v-model.number="dataForm.price" @input="handleMoneyInput(0)" clearable></el-input>
          </el-form-item>
          <el-form-item label="平台售价:" prop="salePrice">
            <el-input type="number" v-model.number="dataForm.salePrice" @input="handleMoneyInput(1)" clearable></el-input>
          </el-form-item>
          <el-form-item prop="marketPrice" label="商户原价">
            <el-input type="number" v-model.number="dataForm.marketPrice" @input="handleMoneyInput(4)"
              @blur="handleMarketPriceBlur" clearable>
              <div slot="append">元</div>
            </el-input>
          </el-form-item>
          <el-form-item prop="discount" label="商户折扣比例:">
            <el-input style="position:relative" type="number" v-model.number="dataForm.discount"
               @input="handleDiscountInput" @blur="handleDiscountBlur" clearable>
              <span slot="suffix">%</span>
            </el-input>
          </el-form-item>
          <el-form-item label="成本价:" prop="costPrice">
            <el-input type="number" v-model.number="dataForm.costPrice" @input="handleMoneyInput(2)" @blur="handleCostBlur" clearable></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item prop="packageFee" label="包装费:">
            <el-input type="number" v-model.number="dataForm.packageFee" clearable
              @input="handleMoneyInput(3)"></el-input>
          </el-form-item>
          <el-form-item prop="packageFlag" label="包装费计算方式">
            <el-radio v-model="dataForm.packageFlag" :label="1">独立包装费</el-radio>
            <el-radio v-model="dataForm.packageFlag" :label="2">合并包装费</el-radio>
          </el-form-item>
          <el-form-item prop="fastFlag" label="是否需配送费:">
            <el-radio v-model="dataForm.deliveryFlag" :label="1">是</el-radio>
            <el-radio v-model="dataForm.deliveryFlag" :label="0">否</el-radio>
          </el-form-item>
        </el-row>

      </el-form>
      <div class="title" v-if="dataForm.ghModelId">
        可售时间
      </div>
      <el-row style="width:96%;margin:0 auto;" v-if="dataForm.ghModelId">
        <el-table :data="dataForm.goodsHours" style="width:fit-content;margin-bottom:10px">
          <el-table-column type="index" label="序号" align="center" width="100px">
          </el-table-column>
          <el-table-column prop="beginHours" label="开始时间" align="center" width="200">
          </el-table-column>
          <el-table-column prop="endHours" label="结束时间" align="center" width="200">
          </el-table-column>
          <el-table-column prop="estimateTime" label="最快到达时间" align="center" width="200">
            <template slot-scope="scope">
              {{ scope.row.estimateTime }}{{ formatTimeUnit(scope.row.timeUnit) }}
            </template>
          </el-table-column>
          <el-table-column prop="deliveryTime" label="可送时间段" align="center" width="200">
          </el-table-column>
          <el-table-column prop="businessRemindTime" label="商户提醒时间(分)" align="center" width="140">
          </el-table-column>
          <el-table-column prop="waiterRemindTime" label="服务员提醒时间(分)" align="center" width="140">
          </el-table-column>
        </el-table>
      </el-row>
      <div class="title">
        产品视频图片
      </div>
      <el-row style="width: 96%;margin: 0 auto;">
        <div class="flex-box">
          <div class="server-img">
            <span class="label">*</span>
            货品视频图片
          </div>
          <div class="btn-wrapper">
            <el-checkbox v-model="dataForm.imagesSave">
              同步上传至公共图库
            </el-checkbox>
          </div>
          <div class="btn-wrapper">
            <el-button type="danger" size="mini" @click="showImageSelectDialog = true">复制公共图库</el-button>
          </div>
        </div>
        <UploadOssFile :list="fileList" @getImgVideo="getImgVideo" folder="serverImg"></UploadOssFile>
      </el-row>

      <div class="title">组合产品</div>
      <el-row style="width: 96%;margin: 0 auto;">
        <el-button @click="handleAddServerComboItem" style="margin-bottom:10px" icon="fa fa-plus" size="mini"
          type="primary">
          新增组合产品项
        </el-button>
        <el-collapse v-model="activeNames">
          <el-collapse-item :name="item.id" v-for="(item, index) in dataForm.serverCombos" :key="item.id">
            <template slot="title">
              {{ item.comboName || "未命名" }}
            </template>
            <el-row>
              <div class="header">
                <div class="item">
                  <div class="label">
                    组合名
                  </div>
                  <div class="value">
                    <el-input size="small" v-model="item.comboName"></el-input>
                  </div>
                </div>
                <div class="item">
                  <div class="label">
                    组合产品
                  </div>
                  <div class="value">
                    <el-cascader @change="handleServerComboItemChange(item)" clearable filterable v-model="item.serverIds"
                      :options="serverList" :props="{ label: 'name', value: 'tempId', multiple: true,emitPath:false }">

                    </el-cascader>
                  </div>
                </div>
                <div class="item">
                  <div class="label">
                    选择个数
                  </div>
                  <div class="value">
                    <el-input size="small" @input="handleChooseNumsInput(item)" v-model="item.chooseNums"></el-input>
                  </div>
                </div>
                <div class="item" style="justify-content:flex-end;flex:1">
                  <el-button type="danger" size="mini" @click="delServerComboItem(index)">
                    删除
                  </el-button>
                </div>
              </div>
              <el-table class="sort-table"  row-key="relationVariantId" :data="item.list" :header-cell-style="{ 'background-color': '#F7F7F7' }"
                style="border-top:1px solid #EBEEF5">
                <el-table-column  label="产品名" align="center">
                  <template slot-scope="scope">
                    <div>
                      {{ formatServerName(scope.row) }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="stock" label="库存" align="center" width="200">

                </el-table-column>
                <el-table-column prop="sort" label="排序(拖拽排序)" align="center">
                  <template slot-scope="scope">
                    {{ scope.$index + 1 }}
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-row>
      <div class="title">
        商品详情描述
      </div>
      <el-row style="width: 96%;margin: 0 auto;">
        <div class="introduce">
          <div class="item">
            <div class="label">
              产品简介
            </div>
            <el-input rows="4" type="textarea" maxlength="200" show-word-limit v-model="dataForm.introduce" placeholder="请输入货品简介"></el-input>
          </div>
          <div class="item">
            <div class="label">
              备注
            </div>
            <el-input rows="4" type="textarea" v-model="dataForm.remark" placeholder="请输入备注"></el-input>
          </div>
        </div>
        <RichEditor :richText="dataForm.describes" @getRichText="getRichText"></RichEditor>
      </el-row>
      <el-row class="bottom"
        :style="{ width: !$store.getters.sidebar.opened ? 'calc(100vw - 87px)' : 'calc(100vw - 239px)' }">
        <div class="wrapper">
          <div class="back" @click="returnList">
            返回
          </div>
          <!-- <div v-if="dataForm.serverId" @click="sureClick(1)">
            保存并同步修改经营产品
          </div> -->
          <div class="save" @click="sureClick()">
            保存
          </div>
        </div>
      </el-row>
    </div>

    <ImageSelect :show="showImageSelectDialog" folder="serverImg" :limit="limitNum"
      @cancel="showImageSelectDialog = false" @getUrlList="getUrlList"></ImageSelect>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import { nanoid } from "nanoid"
import BusinessServerApi from '@/api/goods/businessServer';
import BusinessApi from "@/api/business/business";
import ServerClassifyApi from "@/api/server/serverClassify"
import BusinessDepartApi from "@/api/business/depart"
import { getStorage } from '@/utils/auth'
import { USER_INFO } from "@/constants/storeName"
import UploadImg from "../../components/UploadImg.vue";
import GoodsSpec from "../../components/GoodsSpec.vue";
import RichEditor from "../../components/RichEditor.vue";
import UploadOssFile from "../../components/UploadOssFile.vue";
import ImageSelect from "../../components/ImageSelect.vue";
import Sortable from "sortablejs"
import TimeTemplateApi from '@/api/goods/timeTemplate';
export default {
  data() {
    return {
      activeNames: [0],
      cascaderKey: 1,
      dataForm: {
        serverId: "",
        //sort:"",
        businessId: "",
        classifyIds: [],
        name: "",
        departIds: [],
        businessServerImages: [],
        introduce: "",
        describes: "",
        businessConfirmWay:1,
        visitFlag: 1,//是否上门，1代表是
        shopFlag: 0,//是否到店，1代表是，0代表不是
        remoteFlag: 0,//是否远程，1代表是，0代表不是
        fastFlag: 0,//紧急通知
        deliveryFlag: 1,//是否需配送费
        packageFlag:1,
        marketPrice:"",
        price: "",
        discount: "",
        salePrice: "",
        costPrice: "",
        deliveryFee: "",
        packageFee: "",
        remark: "",
        serverCode: "",
        serverCombos: [],
        ghModelId: "",
        imagesSave: false,
        businessClassifyIds:[],
        goodsHours: [
        ],
      },
      fileList: [],
      businessList: [],
      treeThreeServerList: [],
      loadingIns: false,
      roleRules: {
        businessId: [
          { required: true, message: "请选择商户", trigger: "change" }
        ],
        name: [
          { required: true, message: "请输入产品名称", trigger: "blur" }
        ],
        classifyIds: [
          { required: true, message: "请选择产品分类", trigger: "blur" }
        ],
        price: [
          { required: true, type: 'number', message: "请输入平台原价", trigger: "blur" }
        ],
        salePrice: [
          { required: true, type: 'number', message: "请输入平台售价", trigger: "blur" }
        ],
        costPrice: [
          { required: true, type: 'number', message: "请输入成本价", trigger: "blur" }
        ],
        marketPrice: [
          { required: true, type: 'number', message: "请输入商户原价", trigger: "blur" }
        ],
        discount: [
          { required: true, type: "number", message: "请输入收费比例", trigger: "blur" }
        ],
      },
      departList: [],
      serverList: [],
      goodsHoursList: [],
      businessConfirmWayList:[
         {id:1,name:'手动确认'},
         {id:2,name:"自动确认"},
         {id:3,name:"支付后自动确认"}
      ],
      showImageSelectDialog: false,
      limit: 5,
      businessClassifyList:[],

    }
  },
  components: {
    UploadImg,
    GoodsSpec,
    RichEditor,
    UploadOssFile,
    ImageSelect,
  },
  computed: {
    mainImg() {
      let val = this.dataForm.businessServerImages.find(item => item.mainFlag)
      return val ? val.url : ""
    },
    limitNum() {
      return this.limit - this.dataForm.businessServerImages.length
    }
  },
  watch: {
    treeThreeServerList() {
      this.cascaderKey++
    },
    'dataForm.serverCombos': {
      handler(newVal) {
        newVal.forEach((item, index) => {
          if (item.list.length && !item.list.some(item2 => item2.draggable)) {
            this.$nextTick(() => {
              this.initSort({ index })
            })
          }
        })
      },
      immediate: true,
      deep: true
    },
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.getBusinessList()
      if (this.$route.query.id) {
        this.dataForm.serverId = this.$route.query.id
        this.getData()
      } else {
        const { businessId } = this.$route.params
        this.dataForm.businessId = businessId
        this.getTreeThreeServerList()
        this.getDepartList()
        this.getBusinessServerHoursList()
        this.getBusinessClassifyList()
      }
    },
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    getData() {
      BusinessServerApi.getBusinessServerInfo({
        id: this.dataForm.serverId
      }).then(res => {
        this.$Utils.bindingBean(this.dataForm, res.data)
        this.getBusinessServerHoursList()
        this.getBusinessClassifyList()
        // 全部送过来
        this.formatData(res.data)
        this.initSort({ type: true })
      })
    },
    // 格式化为所需的数据
    formatData(data) {
      // 这里需要将二三级分类id变为数组
      const classifyIds = []
      data.serverClassifyId ? classifyIds.push(data.serverClassifyId) : ""
      data.thirdClassifyId ? classifyIds.push(data.thirdClassifyId) : ''
      data.classifyIds = classifyIds
      // 将四级部门合并为数组
      const departIds = []
      data.departId ? departIds.push(data.departId) : ""
      data.firstDepartId ? departIds.push(data.firstDepartId) : ""
      data.secondDepartId ? departIds.push(data.secondDepartId) : ""
      data.thirdDepartId ? departIds.push(data.thirdDepartId) : ""
      data.departIds = departIds

       // 如果存在商户分类就需要获取
       data.businessClassifyIds = (data.businessClassifies || []).map(item => item.id)

      this.dataForm.classifyIds = classifyIds
      this.dataForm.departIds = departIds
      this.dataForm.businessClassifyIds = data.businessClassifyIds
      this.getTreeThreeServerList()
      this.getDepartList()
      this.getServerList()

      //图片深度克隆一下
      this.fileList = JSON.parse(JSON.stringify(data.businessServerImages || []))
      // 对套餐组合进行格式化数据
      this.dataForm.serverCombos.forEach(item => {
        this.$set(item, 'id', nanoid())
        this.$set(item, 'serverIds', item.list.map(item => item.relationVariantId))
        // item.list.forEach(item => {
        //   this.$set(item, 'serverId', item.relationServerId)
        // })
        this.activeNames.push(item.id)
      })
    },
    initSort({ index, type }) {
      const { serverCombos } = this.dataForm
      if (!type) {
        serverCombos[index].list.forEach(item => item.draggable = true)
        const el = document.querySelectorAll('.sort-table .el-table__body-wrapper > table > tbody')[index]
        new Sortable(el, {
          onEnd: (evt) => { // 监听拖动结束事件
            // 这里就可以写我们需要传给后台的逻辑代码
            // 我们有了 evt.oldIndex 和 evt.newIndex 这两个参数做索引，我们可以根据绑定在表格上面的 data 这个 Array 找到两个相应的记录。就可以针对数据进行操作啦。
            // 下面将拖拽后的顺序进行修改
            const currRow = serverCombos[index].list.splice(evt.oldIndex,1)[0]
            serverCombos[index].list.splice(evt.newIndex,0,currRow)
          }
        })
      } else if (type) {
        // this.$set(serverCombos[index],'draggable',true)
        const el = document.querySelectorAll('.el-collapse')[0]
        new Sortable(el, {
          onEnd: (evt) => { // 监听拖动结束事件
            // 这里就可以写我们需要传给后台的逻辑代码
            // 我们有了 evt.oldIndex 和 evt.newIndex 这两个参数做索引，我们可以根据绑定在表格上面的 data 这个 Array 找到两个相应的记录。就可以针对数据进行操作啦。
            // 下面将拖拽后的顺序进行修
            const currRow = serverCombos.splice(evt.oldIndex,1)[0]
            serverCombos.splice(evt.newIndex,0,currRow)
          }
        })
      }

    },
    async getBusinessClassifyList () {
      const res = await BusinessServerApi.classifyListIdName({businessId: this.dataForm.businessId})
      this.businessClassifyList = res.data
    },
    formatServerName(row){
      const {relationServerName,relationVariantSku} = row
      if(relationVariantSku&&relationVariantSku!='无'){
        return relationServerName+'/'+relationVariantSku
      }else{
        return relationServerName
      }
    },
    getDepartList() {
      BusinessDepartApi.listMangerTree({ businessId: this.dataForm.businessId }).then(res => {
        this.setDisabled(res.data)
        this.departList = res.data
      })
    },
    setDisabled(list) {
      list.forEach(item => {
        if (!item.power) {
          item.disabled = true
        }
        if (item.children) {
          this.setDisabled(item.children)
        }
      })
    },
    handleGhModelIdChange() {
      const { dataForm, goodsHoursList } = this
      dataForm.goodsHours = []
      if (!dataForm.ghModelId) return
      const val = goodsHoursList.find(item => item.modelId == dataForm.ghModelId)
      if (val) {
        dataForm.goodsHours = val.relations
      }
    },
    formatTimeUnit(cell) {
      if (cell == 1) {
        return "分钟"
      } else if (cell == 2) {
        return "时"
      } else {
        return ""
      }
    },
    getBusinessServerHoursList() {
      TimeTemplateApi.listIdName({ businessId: this.dataForm.businessId }).then(res => {
        this.goodsHoursList = res.data
      })
    },
    getUrlList(val) {
      this.fileList = JSON.parse(JSON.stringify(this.dataForm.businessServerImages.concat(val)))
      this.showImageSelectDialog = false
    },
    getRichText(val) {
      this.dataForm.describes = val
    },
    // 新增组合产品项
    handleAddServerComboItem() {
      const { serverCombos } = this.dataForm
      serverCombos.push({
        id: nanoid(),
        comboName: "",
        serverIds: [],
        chooseNums: "",
        list: []
      })
      this.activeNames.push(serverCombos.at(-1).id)
    },
    // 删除组合产品项
    delServerComboItem(index) {
      this.dataForm.serverCombos.splice(index, 1)
    },
    // 组合产品项改变
    handleServerComboItemChange(val) {
      const { serverIds } = val
      const arr = []
      serverIds.forEach(item=>{
        this.serverList.find(item2=>{
          if(item2.variantId==item){
            return arr.push({
              relationVariantId: item2.tempId,
              relationServerName: item2.name,
              stock: item2.stock,
              relationServerId:item2.id,
            })


          }else if(item2.children && item2.children.length){
            return item2.children.find(item3=>{
              if(item3.tempId==item){
                return arr.push({
                  relationVariantId: item3.tempId,
                  relationServerName: item2.name,
                  relationVariantSku:item3.sku,
                  stock:item3.stock,
                  relationServerId:item3.id,
                })
              }
            })

          }
        })
      })
      val.list = JSON.parse(JSON.stringify(arr))
      val.chooseNums = ""
    },
    // 商户改变
    handleBusinessIdChange() {
      this.dataForm.classifyIds = []
      this.treeThreeServerList = []
      this.dataForm.departIds = []
      this.departList = []
      this.goodsHoursList = []
      this.dataForm.ghModelId = ""
      this.dataForm.goodsHours = []
      this.dataForm.businessClassifyIds = []
      this.dataForm.businessClassifyList = []
      if (this.dataForm.businessId) {
        this.getTreeThreeServerList()
        this.getDepartList()
        this.getBusinessServerHoursList()
        this.getBusinessClassifyList()
      }
    },
    // 产品分类改变
    handleClassifyIdsChange() {
      const { classifyIds, serverCombos } = this.dataForm
      this.serverList = []
      serverCombos.forEach(item => {
        item.serverIds = []
        item.list = []
        item.chooseNums = ""
      })
      if (classifyIds.length) {
        this.getServerList()
      }
    },
    // 获取产品列表
    getServerList() {
      const { businessId, classifyIds } = this.dataForm
      const params = {
        businessId,
        thirdClassifyId: classifyIds.at(-1),
      }
      BusinessServerApi.businessServerTree(params).then(res => {
        const data = res.data || []
        data.forEach(item => {
          item.tempId = item.variantId||item.id
          const children = item.children
          if (children && children.length) {
            children.forEach(item => {
              item.name = item.sku
              item.tempId = item.variantId
            })
          }
        })
        this.serverList = JSON.parse(JSON.stringify(data))
      })
    },
    // 获取上传的文件列表
    getImgVideo(val) {
      this.dataForm.businessServerImages = val
    },
    // 获取商户列表
    getBusinessList() {
      BusinessApi.listIdNameVo().then(res => {
        this.businessList = res.data
        // this.getTreeThreeServerList()
      })
    },
    // 获取二三级服务列表
    getTreeThreeServerList() {
      let params = {
        level: 2,
        businessId: this.dataForm.businessId
      }
      ServerClassifyApi.listServerClassify(params).then(res => {
        this.treeThreeServerList = res.data
      })
    },
    // 价格或者配送费改变,需要计算出售价
    handleMoneyChange() {
      let price = this.dataForm.price || 0
      let deliveryFee = this.dataForm.deliveryFee || 0
      this.dataForm.salePrice = parseFloat((price + deliveryFee).toFixed(2))
    },
    // 商户原价改变
    handleMarketPriceBlur() {
      const { marketPrice, discount, costPrice } = this.dataForm
      if (costPrice && marketPrice && costPrice > marketPrice) {
        this.dataForm.marketPrice = ""
        this.dataForm.discount = ""
        this.$message.error("商户原价不能小于成本价")
        return
      }
      this.dataForm.costPrice = parseFloat((marketPrice * discount / 100).toFixed(4))
    },
    // 商户折扣比例改变
    handleDiscountBlur() {
      const { marketPrice, discount } = this.dataForm
      this.dataForm.costPrice = parseFloat((marketPrice * discount / 100).toFixed(4))
    },
    handleCostBlur() {
      const { costPrice, marketPrice } = this.dataForm
      if (costPrice == 0) {
        return
      }
      if (costPrice && marketPrice && costPrice > marketPrice) {
        this.dataForm.marketPrice = ""
        this.dataForm.discount = ""
        this.$message.error("成本价不能大于商户原价")
        return
      }
      this.dataForm.discount = parseFloat((costPrice / marketPrice * 100).toFixed(2))
    },
    handleMoneyInput(flag) {
      if (!flag) {
        // 只保留两位小数
        this.dataForm.price = parseFloat(parseFloat(this.dataForm.price).toFixed(2))
        !this.dataForm.price ? this.dataForm.price = 0 : ""
      } else if (flag == 1) {
        this.dataForm.salePrice = parseFloat(parseFloat(this.dataForm.salePrice).toFixed(2))
        !this.dataForm.salePrice ? this.dataForm.salePrice = 0 : ""
      } else if (flag == 2) {
        // 只保留两位小数
        this.dataForm.costPrice = parseFloat(parseFloat(this.dataForm.costPrice).toFixed(4))
        !this.dataForm.costPrice ? this.dataForm.costPrice = 0 : ""
      } else if (flag == 3) {
        // 只保留两位小数
        this.dataForm.packageFee = parseFloat(parseFloat(this.dataForm.packageFee).toFixed(2))
        !this.dataForm.packageFee ? this.dataForm.packageFee = 0 : ""
      }else if (flag == 4) {
        this.dataForm.marketPrice = parseFloat(parseFloat(this.dataForm.marketPrice).toFixed(2))
        !this.dataForm.marketPrice ? this.dataForm.marketPrice = 0 : ""
      }
    },
    // 平台比例输入的时候
    handleDiscountInput() {
      this.dataForm.discount = parseFloat(parseFloat(this.dataForm.discount).toFixed(2))
      if (this.dataForm.discount && this.dataForm.discount > 99.72) {
        this.dataForm.discount = 0
        this.$message.error("商户折扣比例只能是0-99.72之间")
      } else if (this.dataForm.discount) {
        this.dataForm.discount = parseFloat(parseFloat(this.dataForm.discount).toFixed(2))
      } else {
        this.dataForm.discount = 0
      }
    },
    // 输入个数
    handleChooseNumsInput(val) {
      if (val.list.length == 0) {
        val.chooseNums = ""
        return
      }
      const arr = String(val.list.length).split("")
      let reg = null
      switch (arr.length) {
        case 1:
          reg = new RegExp(`^[1-${arr[0]}]$`)
          break
        case 2:
          if (arr[0] > 1) {
            const temp = arr[0] - 1
            reg = new RegExp(`(^[1-9]$)|(^[1-${temp}][0-9]$)|(^${arr[0]}[0-${arr[1]}]$)`)
          } else {
            reg = new RegExp(`(^[1-9]$)|(^1[0-${arr[1]}]$)`)
          }
          break
        default:
          val.chooseNums = ""
          return
      }
      reg.test(val.chooseNums) ? "" : val.chooseNums = ""
    },
    checkData() {
      let { serverCombos } = this.dataForm
      let flag = false
      this.dataForm.serverCombos = serverCombos = serverCombos.filter(item => item.serverIds.length)
      flag = serverCombos.some(item => {
        // if (!String(item.list.stock).length) {
        //   this.$message.error("请将库存填写完整")
        //   return true
        // }

        if (!item.comboName) {
          this.$message.error("请填写组合名称")
          return true
        }

      })

      if (flag) return
      this.serverCombos = serverCombos.map((item, index) => {
        const obj = { ...item }
        delete obj.id
        delete obj.serverIds
        obj.sort = index + 1
        obj.list = obj.list.map((item2, index2) =>{
          const temp = {...item2}
          delete temp.draggable
          return Object.assign(temp, { sort: index2 + 1 })
        })
        return obj
      })
      return true


    },
    async sureClick(isUpdate) {
      if (!this.checkData()) return
      const res = await Promise.all([this.$refs.dataForm.validate(), this.$refs.dataForm2.validate()])
      if (!res) return
      this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {})
        .then(() => {
          if (this.dataForm.serverId) {
            this.editData(isUpdate);
          } else {
            this.addData();
          }
        });

      // this.$refs.dataForm.validate(valid => {
      //   if (valid) {
      //     // 这里做下校验而且也获取所需要提交的数据
      //     if (!this.checkData()) return
      //     this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {})
      //       .then(() => {
      //         if (this.dataForm.serverId) {
      //           this.editData(isUpdate);
      //         } else {
      //           this.addData();
      //         }
      //       });
      //   }
      // })
    },
    addData() {
      let param = {
        businessId: this.dataForm.businessId,
        serverClassifyId: this.dataForm.classifyIds[0] ? this.dataForm.classifyIds[0] : "",
        thirdClassifyId: this.dataForm.classifyIds[1] ? this.dataForm.classifyIds[1] : "",
        name: this.dataForm.name,
        departId: this.dataForm.departIds[0] || "",
        firstDepartId: this.dataForm.departIds[1] || "",
        secondDepartId: this.dataForm.departIds[2] || "",
        thirdDepartId: this.dataForm.departIds[3] || "",
        businessServerImages: this.dataForm.businessServerImages,
        introduce: this.dataForm.introduce,
        describes: this.dataForm.describes,
        businessConfirmWay:this.dataForm.businessConfirmWay,
        visitFlag: this.dataForm.visitFlag,
        shopFlag: this.dataForm.shopFlag,
        remoteFlag: this.dataForm.remoteFlag,
        fastFlag: this.dataForm.fastFlag,
        deliveryFlag: this.dataForm.deliveryFlag,
        packageFlag:this.dataForm.packageFlag,
        price: this.dataForm.price,
        discount: this.dataForm.discount,
        salePrice: this.dataForm.salePrice,
        costPrice: this.dataForm.costPrice,
        packageFee: this.dataForm.packageFee,
        remark: this.dataForm.remark,
        serverCombos: this.serverCombos,
        serverType: 2,
        variantState: 1,
        marketPrice: this.dataForm.marketPrice,
        goodsHours: this.dataForm.goodsHours,
        ghModelId: this.dataForm.ghModelId,
        imagesSave: this.dataForm.imagesSave,
        businessClassifyIds:this.dataForm.businessClassifyIds,
      };
      BusinessServerApi.addCombo(param).then(res => {
        this.$Utils.notifySuccess()
        this.returnList();
      })
    },
    editData(isUpdate) {
      let param = {
        serverId: this.dataForm.serverId,
        businessId: this.dataForm.businessId,
        serverClassifyId: this.dataForm.classifyIds[0] ? this.dataForm.classifyIds[0] : "",
        thirdClassifyId: this.dataForm.classifyIds[1] ? this.dataForm.classifyIds[1] : "",
        name: this.dataForm.name,
        departId: this.dataForm.departIds[0] || "",
        firstDepartId: this.dataForm.departIds[1] || "",
        secondDepartId: this.dataForm.departIds[2] || "",
        thirdDepartId: this.dataForm.departIds[3] || "",
        businessServerImages: this.dataForm.businessServerImages,
        introduce: this.dataForm.introduce,
        describes: this.dataForm.describes,
        businessConfirmWay:this.dataForm.businessConfirmWay,
        visitFlag: this.dataForm.visitFlag,
        shopFlag: this.dataForm.shopFlag,
        remoteFlag: this.dataForm.remoteFlag,
        fastFlag: this.dataForm.fastFlag,
        deliveryFlag: this.dataForm.deliveryFlag,
        packageFlag:this.dataForm.packageFlag,
        price: this.dataForm.price,
        discount: this.dataForm.discount,
        salePrice: this.dataForm.salePrice,
        costPrice: this.dataForm.costPrice,
        packageFee: this.dataForm.packageFee,
        remark: this.dataForm.remark,
        serverCode: this.dataForm.serverCode,
        serverCombos: this.serverCombos,
        serverType: 2,
        variantState: 1,
        marketPrice: this.dataForm.marketPrice,
        goodsHours: this.dataForm.goodsHours,
        ghModelId: this.dataForm.ghModelId,
        imagesSave: this.dataForm.imagesSave,
        businessClassifyIds:this.dataForm.businessClassifyIds,
      };
      if (isUpdate) {
        param.update = isUpdate
      }
      BusinessServerApi.editBusinessServer(param)
        .then(data => {
          this.$Utils.notifySuccess()
          this.returnList();
        })
    },
    returnList() {
      this.$store.dispatch('delView', this.$route);
      this.$router.back()
    }
  },

}
</script>
<style lang="scss" scoped>
@import "@/assets/css/views/serverAdd.scss";
</style>
<style lang="scss" scoped>
.flex-box {
  display: flex;
  align-items: center;

  &>div {
    margin-right: 10px;
  }

  .server-img {
    position: relative;
    font-size: 14px;

    .label {
      color: red;
      position: absolute;
      top: 0;
      left: -12px;
    }
  }
}

// .disabled-select {
//   ::v-deep .el-input.is-disabled .el-input__inner {
//     color: #606266;
//   }
// }

.el-collapse {
  border: 1px solid #E6E6E6;
  margin: 0 15px 20px 0;

  &::v-deep .el-collapse-item__header {
    justify-content: center;
    background-color: #F7F7F7;
    border-top: 1px solid #E6E6E6;
    border-bottom: 1px solid #E6E6E6;
    height: 38px;
    line-height: 38px;
    font-weight: 800;

    .el-collapse-item__arrow {
      margin: 0;
    }
  }

  .el-collapse-item {

    &::v-deep .el-collapse-item__wrap {
      border: none;

      .el-collapse-item__content {
        padding-bottom: 0;

        .el-row {
          margin: 20px;

          .el-table {
            border: 1px solid #E6E6E6;
          }
        }
      }
    }

    .header {
      display: flex;
      padding-right: 20px;

      .item {
        display: flex;
        align-items: center;
        padding: 10px 0;

        .el-select {
          ::v-deep input {
            // line-height: 30px !important;
          }

          // ::v-deep .el-input__icon {
          //   line-height: 30px
          // }
        }

        .el-input {
          ::v-deep input {
            height: 40px !important;
            line-height: 40px !important;
          }
        }

        .label {
          width: 80px;
          box-sizing: border-box;
          padding-right: 10px;
          text-align: end
        }
      }
    }


  }

}

.introduce {
  margin-bottom: 10px;
  font-size: 14px;
  display: flex;
  width: 1000px;
  justify-content: space-between;

  .item {
    width: 46%;
    display: flex;
    text-align: end;

    .label {
      width: 80px;
      padding-right: 7px;
    }
  }

}
</style>
